#include "ObjectManager.h"
#include "Wrappers/CSGD_FModManager.h"
#include "Messaging/CSGP_MessageSystem.h"
#include "Game Objects/CBase.h"

#include "CGame.h"
#include "Game Objects\CPlayer.h"

ObjectManager* ObjectManager::objMan = NULL;

ObjectManager::ObjectManager(void)
{

}

ObjectManager::~ObjectManager(void)
{

}

void ObjectManager::UpdateObjects(float fElapsedTime)
{
	// start iterator at beginning of list of objects
	vector<IBaseInterface*>::iterator iter = m_vObjectList.begin();

	while(iter != m_vObjectList.end())
	{
		(*iter)->Update(fElapsedTime);
		iter++;
	}
}

void ObjectManager::RenderObjects(void)
{

	for(unsigned int fruit=0; fruit < m_vObjectList.size(); fruit++) // <-- Hey look! A fruit loop!
	{
		m_vObjectList[fruit]->Render();
	}
}

void ObjectManager::AddObject(IBaseInterface* pObject)
{
	// Error checking
	if(pObject == NULL)
		return;

	// Add object to list
	m_vObjectList.push_back(pObject);

	// Call Addref
	pObject->AddRef();
}

void ObjectManager::RemoveObject(IBaseInterface* pObject)
{
	// Error checking
	if(pObject == NULL)
		return;

	// Loop through object list
	for(vector<IBaseInterface*>::iterator iter = m_vObjectList.begin();
		iter != m_vObjectList.end();
		iter++)
	{
		if((*iter) == pObject)
		{
			// Remove reference
			(*iter)->Release();

			// Remove Object
			iter = m_vObjectList.erase(iter);
			break;
		}
	}
}

void ObjectManager::RemoveAllObjects(void)
{
	// Release all objects
	for(unsigned int i=0; i<m_vObjectList.size(); i++)
	{
		m_vObjectList[i]->Release();
	}

	// Clear out the vector
	m_vObjectList.clear();
}

ObjectManager* ObjectManager::GetInstance(void)
{
	if(objMan == NULL)
		objMan = new ObjectManager;

	return objMan;
}

void ObjectManager::DeleteInstance(void)
{
	if(objMan != 0)
	{
		delete objMan;
		objMan = NULL;
	}
}

bool ObjectManager::CheckCollisions()
{
	if(!m_vObjectList.empty())
	{
		for(unsigned int first = 0; first < m_vObjectList.size(); ++first)
		{
			CPlayer::GetInstance()->CheckCollisions(m_vObjectList[first]);
			for(unsigned int second = 1; second < m_vObjectList.size(); ++second)
			{
				if(m_vObjectList[first] == m_vObjectList[second])
					continue;

				m_vObjectList[first]->CheckCollision(m_vObjectList[second]);
			}
		}
	}

	return false;
}